package cn.stylefeng.guns.modular.miniapp.config;

import org.springframework.context.annotation.*;
import org.springframework.boot.context.properties.*;
import cn.binarywang.wx.miniapp.api.*;
import org.springframework.beans.factory.annotation.*;
import cn.binarywang.wx.miniapp.config.impl.*;
import cn.stylefeng.guns.modular.weixin.utils.*;
import cn.binarywang.wx.miniapp.api.impl.*;
import cn.binarywang.wx.miniapp.config.*;
import java.util.stream.*;
import java.util.*;
import javax.annotation.*;
import me.chanjar.weixin.common.session.*;
import cn.binarywang.wx.miniapp.message.*;
import me.chanjar.weixin.common.error.*;
import java.io.*;
import me.chanjar.weixin.common.bean.result.*;
import cn.binarywang.wx.miniapp.builder.*;
import cn.binarywang.wx.miniapp.bean.*;
import com.google.common.collect.*;

@Configuration
@EnableConfigurationProperties({ WxMaProperties.class })
public class WxMaConfiguration
{
    private WxMaProperties properties;
    private static Map<String, WxMaMessageRouter> routers;
    private static Map<String, WxMaService> maServices;
    private final WxMaMessageHandler templateMsgHandler;
    private final WxMaMessageHandler logHandler;
    private final WxMaMessageHandler textHandler;
    private final WxMaMessageHandler picHandler;
    private final WxMaMessageHandler qrcodeHandler;
    
    @Autowired
    public WxMaConfiguration(final WxMaProperties properties) {
        this.templateMsgHandler = ((wxMessage, context, service, sessionManager) -> {
            service.getMsgService().sendTemplateMsg(WxMaTemplateMessage.builder().templateId("\u6b64\u5904\u66f4\u6362\u4e3a\u81ea\u5df1\u7684\u6a21\u677fid").formId("\u81ea\u5df1\u66ff\u6362\u53ef\u7528\u7684formid").data((List)Lists.newArrayList((Object[])new WxMaTemplateData[] { new WxMaTemplateData("keyword1", "339208499", "#173177") })).toUser(wxMessage.getFromUser()).build());
            return null;
        });
        this.logHandler = ((wxMessage, context, service, sessionManager) -> {
            System.out.println("\u6536\u5230\u6d88\u606f\uff1a" + wxMessage.toString());
            service.getMsgService().sendKefuMsg(((TextMessageBuilder)WxMaKefuMessage.newTextBuilder().content("\u6536\u5230\u4fe1\u606f\u4e3a\uff1a" + wxMessage.toJson()).toUser(wxMessage.getFromUser())).build());
            return null;
        });
        this.textHandler = ((wxMessage, context, service, sessionManager) -> {
            service.getMsgService().sendKefuMsg(((TextMessageBuilder)WxMaKefuMessage.newTextBuilder().content("\u56de\u590d\u6587\u672c\u6d88\u606f").toUser(wxMessage.getFromUser())).build());
            return null;
        });
        this.picHandler = ((wxMessage, context, service, sessionManager) -> {
            try {
                final WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", "png", ClassLoader.getSystemResourceAsStream("tmp.png"));
                service.getMsgService().sendKefuMsg(((ImageMessageBuilder)WxMaKefuMessage.newImageBuilder().mediaId(uploadResult.getMediaId()).toUser(wxMessage.getFromUser())).build());
            }
            catch (WxErrorException e) {
                e.printStackTrace();
            }
            return null;
        });
        this.qrcodeHandler = ((wxMessage, context, service, sessionManager) -> {
            try {
                final File file = service.getQrcodeService().createQrcode("123", 430);
                final WxMediaUploadResult uploadResult = service.getMediaService().uploadMedia("image", file);
                service.getMsgService().sendKefuMsg(((ImageMessageBuilder)WxMaKefuMessage.newImageBuilder().mediaId(uploadResult.getMediaId()).toUser(wxMessage.getFromUser())).build());
            }
            catch (WxErrorException e) {
                e.printStackTrace();
            }
            return null;
        });
        this.properties = properties;
    }
    
    public static WxMaService getMaService(final String appid) {
        final WxMaService wxService = WxMaConfiguration.maServices.get(appid);
        if (wxService == null) {
            throw new IllegalArgumentException(String.format("\u672a\u627e\u5230\u5bf9\u5e94appid=[%s]\u7684\u914d\u7f6e\uff0c\u8bf7\u6838\u5b9e\uff01", appid));
        }
        return wxService;
    }
    
    public static WxMaMessageRouter getRouter(final String appid) {
        return WxMaConfiguration.routers.get(appid);
    }
    
    @PostConstruct
    public void init() {
        final List<WxMaProperties.Config> configs = this.properties.getConfigs();
        if (configs == null) {
            throw new RuntimeException("\u5927\u54e5\uff0c\u62dc\u6258\u5148\u770b\u4e0b\u9879\u76ee\u9996\u9875\u7684\u8bf4\u660e\uff08readme\u6587\u4ef6\uff09\uff0c\u6dfb\u52a0\u4e0b\u76f8\u5173\u914d\u7f6e\uff0c\u6ce8\u610f\u522b\u914d\u9519\u4e86\uff01");
        }
        WxMaConfiguration.maServices = configs.stream().map(a -> {
            WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
            config.setAppid(a.getAppid());
            config.setSecret(a.getSecret());
            config.setToken(a.getToken());
            config.setAesKey(a.getAesKey());
            config.setMsgDataFormat(a.getMsgDataFormat());
            Boolean defaultMa = a.getDefaultMa();
            if (defaultMa) {
                WxUtils.maConfig.put("default", a.getAppid());
            }
            WxUtils.maConfig.put(a.getMaName(), a.getAppid());
            WxUtils.maConfig.put(a.getAppid(), a.getMaName());
            WxMaService service = (WxMaService)new WxMaServiceImpl();
            service.setWxMaConfig((WxMaConfig)config);
            WxMaConfiguration.routers.put(a.getAppid(), this.newRouter(service));
            return service;
        }).collect(Collectors.toMap(s -> s.getWxMaConfig().getAppid(), a -> a));
    }
    
    private WxMaMessageRouter newRouter(final WxMaService service) {
        final WxMaMessageRouter router = new WxMaMessageRouter(service);
        router.rule().handler(this.logHandler).next().rule().async(false).content("\u6a21\u677f").handler(this.templateMsgHandler).end().rule().async(false).content("\u6587\u672c").handler(this.textHandler).end().rule().async(false).content("\u56fe\u7247").handler(this.picHandler).end().rule().async(false).content("\u4e8c\u7ef4\u7801").handler(this.qrcodeHandler).end();
        return router;
    }
    
    static {
        WxMaConfiguration.routers = Maps.newHashMap();
        WxMaConfiguration.maServices = Maps.newHashMap();
    }
}
